<?php
/**
 * Created by PhpStorm.
 * Script Name: Base.php
 * Create: 2020/9/6 下午9:14
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;

use app\common\controller\BaseCtl;
use app\admin\model\Admin as AdminM;

class Base extends BaseCtl
{
    protected $module = 'admin';
    /**
     * @var \app\common\model\Base
     */
    protected $model;
    protected $layout = 'layout/base';
    protected $needLogin = true;
    protected $pk = 'id';
    protected $sKey = 'aid';
    protected $botList = [];
    protected $bot;

    /**
     * @var int
     */
    protected $aid;
    protected $adminInfo;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        if($this->needLogin){
            $this->isLogin();
            if(! model('admin/adminGroup')->checkAuth($this->controller.'/'.$this->action, $this->adminInfo)){
                $this->error('暂无权限！');
            }
            $this->bot = $this->getCurrentBot();
            $this->botList = $this->getBots();
            $this->assign['bot_info'] = $this->bot;
            $this->assign['bot_list'] = $this->botList;
        }
    }

    /**
     * check if login
     * Author: fudaoji<fdj@kuryun.cn>
     */
    protected function isLogin(){
        $this->aid = (int)session($this->sKey);
        $this->adminInfo = model("admin/admin")->getOne($this->aid);
        if (empty($this->adminInfo)) {
            cookie('redirect_url', request()->url());
            $this->redirect(url('admin/auth/login'));
        }
        $this->assign['admin'] = $this->adminInfo;
    }

    /**
     * 商户id条件
     * @param string $alias
     * @param null $admin_info
     * @return array
     * Author: fudaoji<fdj@kuryun.cn>
     */
    protected function adminWhere($alias = '', $admin_info = null){
        $alias = $alias ? $alias.'.' : '';
        $admin_info = empty($admin_info) ? $this->adminInfo : $admin_info;
        return [$alias . 'admin_id' => empty($admin_info['pid']) ? $admin_info['id'] : $admin_info['pid']];
    }

    /**
     * 员工条件
     * @param string $alias
     * @param array $admin_info
     * @return array
     * Author: fudaoji<fdj@kuryun.cn>
     */
    protected function staffWhere($alias = '', $admin_info = []){
        $alias = $alias ? $alias.'.' : '';
        $admin_info = empty($admin_info) ? $this->adminInfo : $admin_info;
        if(AdminM::isLeader($admin_info)){
            return [$alias . 'admin_id' => AdminM::getCompanyId($admin_info)];
        }
        return [$alias . 'staff_id' => $admin_info['id']];
    }

    /**
     * 员工所属bot ids
     * @param string $alias
     * @param array $admin_info
     * @return array
     * Author: fudaoji<fdj@kuryun.cn>
     */
    protected function staffBotWhere($alias = '', $admin_info = []){
        $alias = $alias ? $alias.'.' : '';
        $admin_info = empty($admin_info) ? $this->adminInfo : $admin_info;
        if(AdminM::isLeader($admin_info)){
            $where = ['admin_id' => AdminM::getCompanyId($admin_info)];
        }else{
            $where = ['staff_id' => $admin_info['id']];
        }
        $bot_ids = model('admin/bot')->getField('id', $where);
        return [$alias . 'bot_id' => ['in', count($bot_ids) ? $bot_ids : [0]]];
    }

    /**
     * 设置一条或者多条数据的状态
     * @Author  fudaoji<fdj@kuryun.cn>
     */
    public function setStatus() {
        $ids = input('ids/a');
        $status = input('status');

        if (empty($ids)) {
            $this->error('请选择要操作的数据');
        }

        $ids = (array) $ids;
        if($status == 'delete'){
            if($this->model->delByMap([[$this->pk, 'in', $ids]])){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }else{
            $arr = [];
            $msg = [
                'success' => '操作成功！',
                'error'   => '操作失败！',
            ];
            switch ($status) {
                case 'forbid' :  // 禁用条目
                    $data['status'] = 0;
                    break;
                case 'resume' :  // 启用条目
                    $data['status'] = 1;
                    break;
                default:
                    $this->error('参数错误');
                    break;
            }
            foreach($ids as $id){
                $data[$this->pk] = $id;
                $arr[] = $data;
            }
            if($this->model->saveAll($arr)){
                $this->success($msg['success']);
            }else{
                $this->error($msg['error']);
            }
        }
    }

    /**
     * 保存数据
     * @param string $jump_to
     * @param array $data
     * @return mixed
     * @throws \think\Exception
     */
    public function savePost($jump_to = '/undefined', $data=[]){
        $post_data = $data ? $data : input('post.');
        if(empty($post_data[$this->pk])){
            $res = $this->model->addOne($post_data);
        }else {
            $res = $this->model->updateOne($post_data);
        }
        
        if($res){
            $this->success('数据保存成功', $jump_to);
        }else{
            $this->error('数据保存出错');
        }
    }

    protected function getCurrentBot(){
        if(! $bot = session(SESSION_BOT)){
            $bot = model('admin/bot')->getOneByOrder([
                'where' => array_merge($this->staffWhere(), ['status' => 1]),
                'order' => ['alive' => 'desc', 'id' => 'desc']
            ]);
        }
        return $bot;
    }

    public function getBots($where = []){
        $where = array_merge(['status' => 1], $this->staffWhere(), $where);
        return model('admin/bot')->getField(['id','title'], $where);
    }
}